/* @flow */
import React from 'react'
import { AgGridReact } from 'ag-grid-react'
import { TableResize } from 'ag-grid-addons'
import R from 'ramda'
import styles from './Table.css'

type Props = {
  columnDefs: Array<Object>,
  rowData: Array<Object>,
  selectChange: Function,
  select: String,
  currentMess: Object,
  step: number
}
export default class Table extends React.Component {
  props: Props
  gridOptions: Object
  api: Object
  TableResize: Function
  onSelectionChanged: Function
  constructor (props: Props) {
    super(props)
    this.gridOptions = {
      onModelUpdated: () => {
        if (this.api) {
          this.api.sizeColumnsToFit()
        }
      },
      getRowNodeId: function (data) { return data.id },
      onGridReady: (params) => { this.onGridReady(params) },
      rowSelection: 'multiple',
      suppressRowClickSelection: true,
      overlayLoadingTemplate:
      '<span style="padding:10px;background-color: #fff; border: 1px solid #666">数据加载</span>',
      overlayNoRowsTemplate: '<span style="padding:10px;background-color: #fff; border: 1px solid #666">暂无数据</span>',
      enableFilter: true,
      animateRows: true,
      onSelectionChanged: () => {
        this.props.selectChange && this.onSelectionChanged(this.props.selectChange)
      }
    }
    this.TableResize = TableResize.bind(this)
    this.onSelectionChanged = this.onSelectionChanged.bind(this)
  }

  componentDidMount () {
    // if ()
    // setTimeout(() => { this.gridOptions.api.selectAll() }, 100)
  }

  componentWillReceiveProps (nextProps: Object) {
    if (nextProps.currentMess && !R.equals(nextProps.currentMess, this.props.currentMess)) {
      const rowNode = this.gridOptions.api.getRowNode(nextProps.currentMess.id)
      rowNode.setDataValue('status', nextProps.currentMess.status)
      rowNode.setDataValue('message', nextProps.currentMess.message)
    }

    if (nextProps.select && !R.equals(nextProps.select, this.props.select)) {
      setTimeout(() => { this.gridOptions.api.selectAll() }, 100)
    }
  }

  onGridReady (params: Object) {
    this.api = params.api
    this.api.sizeColumnsToFit()
    this.TableResize()
  }
  onSelectionChanged (params: Object) {
    const selectRows = this.gridOptions.api.getSelectedRows()
    // console.info(selectRows)
    this.props.selectChange(selectRows)
  }
  render () {
    const { columnDefs, rowData } = this.props
    return (
      <div className={styles['gardPanelTable']}>
        <AgGridReact
          columnDefs={columnDefs}
          gridOptions={this.gridOptions}
          rowData={rowData}
          enableColResize='true'
          enableSorting='true'
          rowHeight='35'
          quickFilterText=''
          headerHeight='35'
          rowBuffer='50'
          debug='false'
          />
      </div>
    )
  }
}
